// Copyright (C) 2022 Huawei Device Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dbutil

import (
	"context"
	"database/sql"
	"dist/model"
	"dist/utils"
	"fmt"
	"time"

	_ "github.com/lib/pq"
)

var db *sql.DB

var pool *sql.DB

func InitSql(pgsqlConfig model.PgsqlConfig) (*sql.DB, error) {
	var err error
	ip := pgsqlConfig.Ip
	var port = pgsqlConfig.Port
	var user = pgsqlConfig.Username
	var pass = pgsqlConfig.Password
	var dbname = pgsqlConfig.Dbname
	psqlDsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		ip, port, user, pass, dbname)
	db, err = sql.Open("postgres", psqlDsn)
	if err != nil {
		utils.Error.Printf("%s", err)
		return nil, err
	}
	db.SetMaxOpenConns(pgsqlConfig.MaxOpenConns)
	db.SetMaxIdleConns(pgsqlConfig.MaxIdleConns)
	duration, err := time.ParseDuration(pgsqlConfig.MaxIdleTime)
	if err != nil {
		return nil, err
	}
	db.SetConnMaxIdleTime(duration)
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	err = db.PingContext(ctx)
	if err != nil {
		return nil, err
	}
	pool = db
	return db, nil
}

func sqlClose() {
	db.Close()
}
func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

func GetConnection() (*sql.Conn, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	return pool.Conn(ctx)
}

func SetDb(dd *sql.DB) {
	pool = dd
}
